<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入仓库地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在区域" prop="district">
        <el-select v-model="queryParams.district" placeholder="请选择区" @change="handleDistrictChangByParam">
          <el-option v-for="item in districts" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在镇" prop="town">
        <el-select v-model="queryParams.town" placeholder="请选择镇" :disabled="!queryParams.district">
          <el-option v-for="town in selectedDistrictTowns2" :key="town.value" :label="town.label"
                     :value="town.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="仓库等级" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择">
          <el-option
            v-for="dict in dict.type.warehouse_level"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="月租金" prop="monthRental">
        <el-input
          v-model="queryParams.monthRental"
          placeholder="请输入月租金"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:warehouses:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:warehouses:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:warehouses:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basic:warehouses:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="warehousesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index"/>
      <el-table-column label="管理员编号" align="center" prop="managerId"/>
      <el-table-column label="管理员姓名" align="center" prop="managerName"/>
      <el-table-column label="管理员电话" align="center" prop="managerPhoneNumber"/>
      <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
      <el-table-column label="仓库地址" align="center" prop="address"/>
      <el-table-column label="所在区域" align="center" prop="district"/>
      <el-table-column label="所在镇" align="center" prop="town"/>
      <el-table-column label="仓库等级" align="center" prop="level">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.warehouse_level" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column label="月租金" align="center" prop="monthRental" :formatter="formatDecimal" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:warehouses:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basic:warehouses:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="仓库管理员" prop="managerId">
          <el-select v-model="form.managerId" filterable placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in managerOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
              <span style="float: left">{{ item.userName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.nickName}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称"/>
        </el-form-item>
        <el-form-item label="所在区域" prop="district">
          <el-select v-model="form.district" placeholder="请选择区" @change="handleDistrictChangeByForm" style="width: 100%">
            <el-option v-for="item in districts" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在街道镇乡" prop="town">
          <el-select v-model="form.town" placeholder="请选择镇" :disabled="!form.district" style="width: 100%">
            <el-option v-for="town in selectedDistrictTowns" :key="town.value" :label="town.label"
                       :value="town.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入仓库地址"/>
        </el-form-item>
        <el-form-item label="仓库等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="dict in dict.type.warehouse_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="月租金" prop="monthRental">
          <el-input-number v-model="form.monthRental" :min="0" :precision="2" ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listWarehouses, getWarehouses, delWarehouses, addWarehouses, updateWarehouses} from "@/api/basic/warehouses";
import dict from "@/utils/dict";
import {districts, levelOptions, MANAGER_POST_ID} from "@/api/common";

export default {
  name: "Warehouses",
  dicts: ['warehouse_level'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库管理表格数据
      warehousesList: [],
      // 可选择的管理员
      managerOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseName: null,
        address: null,
        district: null,
        town: null,
        level: null,
        monthRental: null,
      },
      levelOptions: levelOptions,
      // 表单参数
      form: {},
      districts: districts,
      watch:{
        form(){
          console.log(this.form)
        }
      },
      // 表单校验
      rules: {
        managerId: [{
          required: true, message: "仓库管理人不能为空", trigger: "change"
        }],
        warehouseName: [
          {required: true, message: "仓库名称不能为空", trigger: "change"}
        ],
        address: [
          {required: true, message: "仓库地址不能为空", trigger: "change"}
        ],
        district: [
          {required: true, message: "所在区域不能为空", trigger: "change"}
        ],
        town: [
          {required: true, message: "所在镇不能为空", trigger: "blur"}
        ],
        level: [
          {required: true, message: "仓库等级不能为空", trigger: "blur"}
        ],
        monthRental: [
          {required: true, message: "月租金不能为空", trigger: "blur"}
        ],
      }
    };
  },
  computed: {
    selectedDistrictTowns() {
      // 根据选择的区，返回对应的镇的数组数据
      return this.form.district ? this.districts.find(item => item.value === this.form.district).towns : [];
    },
    selectedDistrictTowns2() {
      // 根据选择的区，返回对应的镇的数组数据
      return this.queryParams.district? this.districts.find(item => item.value === this.queryParams.district).towns : [];
    }
  },
  created() {
    this.getList();
  },
  methods: {
    formatDecimal(row, column, cellValue) {
      // 假设您想要保留两位小数
      return Number(cellValue).toFixed(2);
    },
    handleDistrictChangeByForm(newVal, oldVal) {
      this.form.town = newVal === oldVal ? this.form.town : null;
    },
    handleDistrictChangByParam(newVal, oldVal) {
      this.queryParams.town = newVal === oldVal ? this.queryParams.town : null;
    },
    /** 查询仓库管理列表 */
    getList() {
      this.loading = true;
      listWarehouses(this.queryParams).then(response => {
        this.warehousesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        warehouseId: null,
        managerId: null,
        warehouseName: null,
        address: null,
        district: null,
        town: null,
        level: null,
        managers: null,
        monthRental: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.warehouseId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      getWarehouses({
        'postId': MANAGER_POST_ID,
        'warehouseId': null,
      }).then(response => {
        this.form = response.data;
        this.managerOptions = response.data.managers
        this.open = true;
        this.title = "修改仓库管理";
      });
      this.title = "添加仓库管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const warehouseId = row.warehouseId || this.ids
      getWarehouses({
        'warehouseId': warehouseId,
        'postId': MANAGER_POST_ID
      }).then(response => {
        this.form = response.data;
        this.managerOptions = response.data.managers
        this.open = true;
        this.title = "修改仓库管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.warehouseId != null) {
            console.log(this.form)
            updateWarehouses(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(this.form)
            addWarehouses(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const warehouseIds = row.warehouseId || this.ids;
      this.$modal.confirm('是否确认删除仓库管理编号为"' + warehouseIds + '"的数据项？').then(function () {
        return delWarehouses(warehouseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/warehouses/export', {
        ...this.queryParams
      }, `warehouses_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
